package host.skiree.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg", "Hello Shiro");
        return "index";
    }

    @RequestMapping({"/user/add"})
    public String toAdd(){
        return "/user/add";
    }

    @RequestMapping({"/user/delete"})
    public String toDelete(){
        return "/user/delete";
    }


    @RequestMapping({"/toLogin"})
    public String toLogin(){
        return "login";
    }


    @RequestMapping({"/login"})
    public String login(String username, String password,Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            subject.login(token);
            model.addAttribute("msg", "尊敬的用户，欢迎您的到来！");
            return "index";
        }catch (UnknownAccountException e) {
            model.addAttribute("msg", "账户错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "密码错误");
            return "login";
        } catch (LockedAccountException lae) {
            model.addAttribute("msg", "账户锁定");
            return "login";
        } catch (Exception e){
            model.addAttribute("msg", "登录异常");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    public String tonoauth(){
        return "noauth";
    }

}
